package day20180131.designMode.sixteen_Observer;

import java.util.Enumeration;
import java.util.Vector;

/**
 * Created by 14394 on 2018/1/31.
 */

//观察者接口
public interface Observer {
    void update();
}

//观察者1
class ObserverImp1 implements  Observer{

    @Override
    public void update() {
        System.out.println("ObserverImp1 update!");
    }
}

//观察者2
class ObserverImp2 implements  Observer{

    @Override
    public void update() {
        System.out.println("ObserverImp2 update!");
    }
}

//目标接口
interface Subject{
    void addObserver(Observer observer);

    void delObserer(Observer observer);

    void notifyObservers();
}

//目标抽象类
abstract class AbstractSubject implements  Subject{
    private Vector<Observer> vector = new Vector<>();

    @Override
    public void addObserver(Observer observer) {
        vector.add(observer);
    }

    @Override
    public void delObserer(Observer observer) {
        vector.remove(observer);
    }

    @Override
    public void notifyObservers() {
        Enumeration<Observer> enumeration= vector.elements();

        while (enumeration.hasMoreElements()){
            enumeration.nextElement().update();
        }
    }

    //具体操作
    abstract void operation();
}

//目标对象
class MySubject extends AbstractSubject{

    @Override
    void operation() {
        System.out.println("Mysubject operation");
        notifyObservers();
    }


/*使用场景：    涉及到一对一或者一对多的对象交互场景都可以使用观察者模式*/
    public static void main(String[] args) {
        MySubject mySubject = new MySubject();

        mySubject.addObserver(new ObserverImp1());

        mySubject.addObserver(new ObserverImp1());

        mySubject.operation();
    }
}